<!-- 播放旋转的圆形图标 -->
<template>
  <div class="circle-progeress">
    <canvas class="canvas" ref="canvas"></canvas>
    <i
      class="iconfont"
      @click="changeAction"
      :class="{ 'icon-bofang': !value, 'icon-zanting1': value }"
    ></i>
  </div>
</template>
<script>
export default {
  props: {
    value: Boolean,
    progress: Number,
  },
  data() {
    return {};
  },
  methods: {
    changeAction() {
      this.$emit("input", !this.value);
    },
    renderCircle() {
      this.context.clearRect(0, 0, 30, 30);
      // 绘制圆弧
      this.context.save();
      this.context.beginPath();
      // 绘制大圆
      this.context.moveTo(15, 15);
      this.context.arc(15, 15, 15, 0, Math.PI * 2, false);
      this.context.lineTo(15, 15);
      // 绘制小圆
      this.context.moveTo(15, 15);
      this.context.arc(15, 15, 12, 0, Math.PI * 2, false);
      this.context.lineTo(15, 15);
      this.context.closePath();
      this.context.fillStyle = "rgba(212,68,57,0.3)";
      this.context.fill("evenodd");
      this.context.restore();

      // 绘制半圆弧
      this.context.save();
      this.context.beginPath();
      // 绘制大圆
      this.context.moveTo(15, 15);
      const startAng = (Math.PI / 180) * -90;
      const endAng =
        (Math.PI / 180) * -90 + (Math.PI / 180) * this.progress * 360;
      // 1° = (π/180)rad ≈ 0.01745rad
      this.context.arc(15, 15, 15, startAng, endAng, false);
      this.context.lineTo(15, 15);
      // 绘制小圆
      this.context.moveTo(15, 15);
      this.context.arc(15, 15, 12, startAng, endAng, false);
      this.context.lineTo(15, 15);
      this.context.closePath();
      this.context.fillStyle = "rgb(212,68,57)";
      this.context.fill("evenodd");
      this.context.restore();
    },
  },
  watch: {
    progress() {
      // console.log("需要重新绘制")
      this.renderCircle();
    },
  },
  //   挂载完成之后就可以操作元素
  mounted() {
    const canvas = this.$refs.canvas;
    //   设置画布大小
    canvas.width = 30;
    canvas.height = 30;
    this.context = canvas.getContext("2d");
    this.renderCircle();
  },
};
</script>
<style lang="scss">
.circle-progeress {
  width: 30px;
  height: 30px;
  // background: #555;
  position: relative;
  .iconfont {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  .canvas {
    position: absolute;
    top: 0;
    left: 0;
    // 不能在css中为canvas设置大小，因为设置了大小是对画布进行了拉伸
  }
}
</style>